var largeurCase = 30;
var hauteurCase = 30;
var tableauJeu = null;

var tableProposition = [];
var iTableProposition = 0;
var TabJeu = [];
var iTabJeu = 0;

var robotSelect = null;
var lastMovedRobotColor = null;
var nbRobots = 0;
var nbDisabledRobots = 0;

function begin() {
    initMap();
    $(document).on('keydown', function(e) {
        if (mode === 'custom' && (e.which || e.keyCode) === 80) {
            openPalette();
        } else if ((e.which || e.keyCode) === 82) {
            initMap();
        }
    });

}

function requeteCustomMap(maps) {
    var login = $('input#login').val();
    var idgame = $('input#idGame').val();
    var configPlateau = JSON.stringify(maps);
    var request = $.ajax({
        url: 'custom',
        type: 'post',
        data: {
            login: login,
            idGame: idgame,
            maps: configPlateau
        },
        success: retourCustomMap
    });
}

function retourCustomMap(data) {
    if (!eraseRobot(data.color)) {
        nbRobots++;
        if (nbRobots === 4) {
            $('#runButton').prop('disabled', false);
        }
    }
    caseRobot(data.l, data.c, data.color);
}

function requetePropostion(proposition) {
    var login = $('input#login').val();
    var idgame = $('input#idGame').val();
    var configPlateau = JSON.stringify(proposition);
    $.ajax({
        url: 'proposition',
        type: 'post',
        data: {
            login: login,
            idGame: idgame,
            proposition: configPlateau
        },
        success: retourProposition
    });
}

function retourProposition(data) {
    if (data.state === 'INVALID_MOVE' || data.state === 'INVALID_SELECT') {
        //Suppression du select et move de la proposition.
        iTableProposition = iTableProposition - 2;
        for (i = iTableProposition; i < (iTableProposition + 2); i++) {
            delete tableProposition[i];
        }
    }
    if (data.state === 'INCOMPLETE' || data.state === 'SUCCESS') {
        
        var newTable = jQuery.extend(true, {}, TabJeu[iTabJeu]);

        robotColor = tableProposition[iTableProposition - 2]['robot'];
        L = tableProposition[iTableProposition - 1]['line'];
        C = tableProposition[iTableProposition - 1]['column'];
        DeplacementRobot(newTable, robotColor, L, C);
        eraseRobot(robotColor);
        caseRobot(L, C, robotColor);
        lastMovedRobotColor = robotColor;
        iTabJeu++;
        TabJeu[iTabJeu] = newTable;
        //hallo sur le robot
        if (data.state === 'INCOMPLETE') {
            position = positionRobot(robotSelect);
            caseShadow(position.l, position.c);
        } else {
            $('canvas.roboselect').removeClass('roboselect');
            disableRobot(robotColor);
        }
    }
}

function DeplacementRobot(table, robotColor, L, C) {
    $.each(table['robots'], function(i, dataRobot) {
        if (dataRobot['color'] === robotColor) {
            dataRobot['line'] = L;
            dataRobot['column'] = C;
        }
    });
}

function caseShadow(l, c) {
    $('canvas.roboselect').removeClass('roboselect');
    $('canvas#L' + l + 'C' + c).addClass('roboselect');
}

function robotAtPosition(l, c) {
    colorrobot = null;
    $.each(TabJeu[iTabJeu]['robots'], function(i, dataRobot) {
        if (dataRobot['line'] === l && dataRobot['column'] === c) {
            colorrobot = dataRobot['color'];
        }
    });
    return colorrobot;
}

function positionRobot(color) {
    colorrobot = null;
    position = null;
    $.each(TabJeu[iTabJeu]['robots'], function(i, dataRobot) {
        if (dataRobot['color'] === color) {
            position = {l: dataRobot['line'], c: dataRobot['column']};
        }
    });
    return position;
}

function clickCanvas(event) {
    L = parseInt(event.target.getAttribute('L'));
    C = parseInt(event.target.getAttribute('C'));
    if (mode === 'custom') {
        if (elementSelectedByPlateau == null) {
            alert('Aucun robot sélectionné !');
            return;
        }
        requeteCustomMap([{element: elementSelectedByPlateau.elem, color: elementSelectedByPlateau.color, l: L, c: C}]);
    } else {
        color = robotAtPosition(L, C);
        if (color !== null) {
            if (!isDisabled(color)) {
                if (robotSelect !== null && color !== robotSelect && robotSelect === lastMovedRobotColor) {
                    disableRobot(robotSelect);
                }
                robotSelect = color;
                caseShadow(L, C);
            }
        } else {
            if (robotSelect !== null) {
                tableProposition[iTableProposition++] = {command: 'select', robot: robotSelect};
                tableProposition[iTableProposition++] = {command: 'move', line: L, column: C};
                requetePropostion(tableProposition);
            }
        }
    }
}


function mapEmpty() {
    map = $('div#map');
    map.empty();

    for (i = 0; i < 16; i++) {
        divLigne = document.createElement('div');
        divLigne.classList.add('ligne');
        divLigne.id = 'l:' + i;
        (function(i) {
            for (c = 0; c < 16; c++) {
                divColonne = document.createElement('canvas');
                divColonne.id = 'L' + i + 'C' + c;
                divColonne.setAttribute('L', i);
                divColonne.setAttribute('C', c);
                divColonne.setAttribute('width', largeurCase);
                divColonne.setAttribute('height', hauteurCase);
                divColonne.classList.add('casemap');
                divColonne.addEventListener('click', clickCanvas, false);
                divLigne.appendChild(divColonne);
            }
        }(i));
        map.append(divLigne);
    }
}

function resetTablePropositions() {
    tableProposition = [];
    iTableProposition = 0;
    TabJeu = [];
    iTabJeu = 0;
}

function initMap() {
    mapEmpty();
    resetTablePropositions();
    nbDisabledRobots=0;
    idgame = $('input#idGame').val();
    $.ajax({
        type: 'GET',
        url: idgame,
        dataType: 'json',
        success: function(data) {
            TabJeu[iTabJeu] = data;
            refresh(data);
            $('#runButton').prop('disabled', true);
        }
    });
}

function refresh(data) {
    $.each(data['board'], refreshLigne);
    $.each(data['robots'], refreshRobot);
    refreshTarget(data['target']);
}

function refreshLigne(nligne, datacolonne) {
    $.each(datacolonne, function(nColonne, dataCase) {
        refreshCase(nligne, nColonne, dataCase);
    });
}

function refreshCase(nligne, ncolonne, datacase) {
    divCase = $('canvas#L' + nligne + 'C' + ncolonne);
    resetClasseMur(divCase);
    $.each(datacase, function(i, val) {
        if (val === 1) {
            divCase.addClass(i);
            var ctx = divCase[0].getContext('2d');
            ctx.beginPath();
            ctx.lineWidth = 3;
            switch (i)
            {
                case 'g':
                    ctx.moveTo(0, 0);
                    ctx.lineTo(0, hauteurCase);
                    break;
                case 'h':
                    ctx.moveTo(0, 0);
                    ctx.lineTo(largeurCase, 0);
                    break;
                case 'd':
                    ctx.moveTo(largeurCase, 0);
                    ctx.lineTo(largeurCase, hauteurCase);
                    break;
                case 'b':
                    ctx.moveTo(0, hauteurCase);
                    ctx.lineTo(largeurCase, hauteurCase);
                    break;
            }
            ctx.stroke();
        }
    });
}

function resetClasseMur(divCase) {
    divCase.attr('class', 'casemap');
}

function refreshRobot(i, dataRobot) {
    caseRobot(dataRobot['line'], dataRobot['column'], dataRobot['color']);
}

function caseRobot(nligne, ncolonne, color) {
    divCase = $('canvas#L' + nligne + 'C' + ncolonne);
    divCase.addClass('R' + color);
    var ctx = divCase[0].getContext('2d');
    var img = new Image();

    switch (color)
    {
        case 'blue':
            img.src = 'img/Blue.png';
            break;
        case 'yellow':
            img.src = 'img/Yellow.png';
            break;
        case 'green':
            img.src = 'img/Green.png';
            break;
        case 'red':
            img.src = 'img/Red.png';
            break;
    }
    img.onload = function() {
        ctx.drawImage(img, (largeurCase / 2) - 15, 0,hauteurCase-5,hauteurCase);
        ctx.beginPath();
        ctx.stroke();
    }

}

function refreshTarget(dataTarget) {
    if (dataTarget !== undefined) {
        caseTarget(dataTarget['l'], dataTarget['c'], dataTarget['t']);
    }
}

function caseTarget(nligne, ncolonne, color) {
    divCase = $('canvas#L' + nligne + 'C' + ncolonne);
    divCase.addClass('T' + color);

    var ctx = divCase[0].getContext('2d');
    ctx.beginPath();
    ctx.arc((largeurCase / 2), (hauteurCase / 2), ((largeurCase / 2) - 4), 0, 2 * Math.PI);
    ctx.fillStyle = color;
    ctx.fill();

    var ctx = divCase[0].getContext('2d');
    ctx.beginPath();
    ctx.arc((largeurCase / 2), (hauteurCase / 2), ((largeurCase / 4) - 4), 0, 2 * Math.PI);
    ctx.fillStyle = '#000000';
    ctx.fill();
}

function eraseRobot(color) {
    canvas = $('.R' + color);
    if (typeof canvas[0] === 'undefined')
        return false;
    canvas[0].getContext('2d').clearRect(0, 0, canvas[0].width, canvas[0].height);

    drawWalls(canvas);
    return true;
}

function getMapCanvasClassesObject(obj) {
    data = {};
    $(obj.attr('class').split(' ')).each(function(i, val) {
        if ($.inArray(val, ['Rred', 'Rblue', 'Ryellow', 'Rgreen', 'casemap']) === -1) {
            data[val] = 1;
        }
    });
    return data;
}

function drawWalls(obj) {
    refreshCase(
            obj.attr('L'),
            obj.attr('C'),
            getMapCanvasClassesObject(obj)
            );
}

function disableRobot(color) {
    var canvas = $('.R' + robotSelect);
    var classAttr = canvas.attr('class');
    var ctx = canvas[0].getContext('2d');
    ctx.globalAlpha = 0.7;
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, largeurCase, hauteurCase);

    drawWalls(canvas);
    canvas.attr('class', classAttr);
    canvas.addClass('disabled');
    nbDisabledRobots++;
    if (nbDisabledRobots === 4 && confirm('Vous êtes bloqué(e). Voulez-vous réinitialiser la grille ?')) {
        initMap();
    }
}

function getPaletteUrl() {
    return 'http://' + window.location.host + '/palette.xhtml?idGame=' + $('#idGame').val();
}

function openPalette() {
    window.open(getPaletteUrl());
    return false;
}

function isDisabled(color) {
    return $.inArray('disabled', $('.R' + color).attr('class').split(' ')) !== -1;
}